
/*******************************************************************************
 * INIZIALIZZAZIONE VARIABILI
 ******************************************************************************/
var shockCircle;
var shockPaper;
var circles = [];
var circlesPaper = [];
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
var isSafari = navigator.userAgent.indexOf("Safari") > -1;
var window_height = 0;
var window_width = 0;
var fade_loader = 500;
var work_switch = 500;
var actual_work = 0;
var section_scroll = 900;

var addendum1 = Math.ceil(Math.random() * 10),
addendum2 = Math.ceil(Math.random() * 10),
sum = addendum1 + addendum2;
var initialWidth = window.innerWidth;

/*******************************************************************************
 * GESTIONE ON READY
 ******************************************************************************/
$(function(){//comincia
    window_height = $(window).height();
    window_width = $(window).width();
    
    if(!isiPhone){
        /**
        * NON MOSTRARE NESSUNA SCROLLBAR
        */
        $('body').css({
            'overflow':'hidden'
        });

        /**
        * TUTTO DEVE AVERE LE MASSIME DIMENSIONI DELLO SCHERMO
        */
        

        $('section.section').width(window_width);
        $('section.section, .section-label').height(window_height);
    
        if($('#home-active-page').size() > 0){
            $('#hide-content').css({
                'position' : 'absolute',
                'left' : 0,
                'top' : 0,
                'z-index' : 50,
                'background-color' : '#fff',
                'width' : window_width,
                'height' : window_height
            });

            $('#foto-wrapper').css({
                'height' : window_height
            });


            /**
            * UN PO'DI MAGIA CON FOUNDANTION
            */
            $('input, textarea').placeholder();
    
            /**
            * POSIZIONA LE SEZIONI FUORI E DENTRO LA VIEWPORT
            */
            $('body').css({
                'opacity':0
            });
            disposeSections();
            //            $('body').show();
        
            /**
            * POSIZIONA LA HOME AL CENTRO DELLA VIEWPORT
            */
            //        alert($('#home-section').offset().top);
			if(isSafari){
				 bodyelem = $('body')
				 bodyelem.animate({
                	scrollTop: $('#home-section').offset().top,
                	
            	}, 100, function(){
                	bodyelem.animate({
						scrollLeft: $('#home-section').offset().left
					}, 100, function(){
						$('body').css({
                    	'opacity':1
                	});
					});
                	
                
            	});
			}
			else{
				 bodyelem = $("html,body")
            	bodyelem.animate({
                	scrollTop: $('#home-section').offset().top,
                	scrollLeft: $('#home-section').offset().left
            	}, 100, function(){
                
                	$('body').css({
                    	'opacity':1
                	});
                
            	});
			}
            
            
        
            if(isiPad || isiPhone){
                $('img').retina();
            
                src = $('.baloon-wrapper.image').data('src');
                newSrc = src.substring(0, src.length - 4)
                newSrc += '@2x.png';
                //            alert(newSrc);
                $('.baloon-wrapper.image').attr('data-src', newSrc);
            }

            /**
            * COLLEGA IL CLICK ALLA NAVIGAZIONE
            */
            $('a.link-section, a.back-link-section').bind('click', goToSection);
    
            //    if(!isiPad && !isiPhone){
            //        if(true){
            shock('#E53159');
            setTimeout(handleBaloons, 1000);
            setTimeout(fadeInSite, 3000);			
            //        }else{
            //            $(document).scroll(slideInSite);
            //        }

            /**
            * COLLEGA IL CLICK PER IL CARICAMENTO DEI LAVORI
            */
            $('.foto-link-loader').bind('click', loadfoto);
    
            /**
            * FAI PARTIRE LA GALLERY PER LA SEZIONE foto
            */
            $('#foto-slides>div').orbit({
                animation: 'fade',
                timer: true,
                animationSpeed: 800,
                directionalNav:false
            });
    
            /**
            * AGGIUNGI IL CONTROLLO UMANO ALLA FORM eksekusi
            */
            $('#addendum1').text(addendum1);
            $('#addendum2').text(addendum2);
            $("#contact-form").submit(contactMe);
    
            /**
            * POSIZIONA AL CENTRO IL CONTENUTO DELLA SEZIONE eksekusi
            */
            $('#eksekusi-content').css('margin-top', (window_height - $('#eksekusi-content').height()) / 2);
            
        }
    }else{
        $('.section').each(function(){
            $(this).css('min-height',window_height);
        });
        
        $('.back-foto-section').text('back');
        
        /**
         * UN PO'DI MAGIA CON FOUNDANTION
         */
        $('input, textarea').placeholder();
        
        /**
         * AGGIUNGI IL CONTROLLO UMANO ALLA FORM eksekusi
         */
        $('#addendum1').text(addendum1);
        $('#addendum2').text(addendum2);
        $("#contact-form").submit(contactMe);
        
        /**
         * COLLEGA IL CLICK PER IL CARICAMENTO DEI LAVORI
         */
        $('#foto-section').remove();
        
        $('#mobile-scroll').bind('click', function(){
			if(isSafari) bodyelem = $("body")
			else bodyelem = $("html,body")
			
            bodyelem.animate({
                scrollTop: $($(this).attr('href')).offset().top
            }, section_scroll);
            
            return false;
        });
    
    }
    
    
    if($('#eksekusi-active-page').size() > 0){
        /**
         * UN PO'DI MAGIA CON FOUNDANTION
         */
        $('input, textarea').placeholder();
        
        /**
         * AGGIUNGI IL CONTROLLO UMANO ALLA FORM eksekusi
         */
        $('#addendum1').text(addendum1);
        $('#addendum2').text(addendum2);
        $("#contact-form").submit(contactMe);
    
        /**
         * POSIZIONA AL CENTRO IL CONTENUTO DELLA SEZIONE eksekusi
         */
        $('#eksekusi-content').css('margin-top', (window_height - $('#eksekusi-content').height()) / 2);
    }
    
    if($('#foto-active-page').size() > 0){
        /**
         * COLLEGA IL CLICK PER IL CARICAMENTO DEI LAVORI
         */
        $('.foto-link-loader').bind('click', loadfoto);
    
        /**
        * FAI PARTIRE LA GALLERY PER LA SEZIONE foto
        */
        $('#foto-slides>div').orbit({
            animation: 'fade',
            timer: true,
            animationSpeed: 900,
            advanceSpeed: 2500, 
            directionalNav:false
        });
    }
    
    /**
     * ASCOLTA PER IL RESIZE
     */
    $(window).resize(handleResize);
});

/*******************************************************************************
 * ANIMAZIONE INIZIALE
 ******************************************************************************/
function shock(color){
    //shock the user 1 time
    var maxWidth = window_width,
    radius = maxWidth;

    shockPaper = new Raphael(document.getElementById('home-section'),window_width, window_height);

    shockCircle = shockPaper.circle(radius / 2, window_height / 2, 1);
    $('body').find('svg').css('z-index', 51);

    shockCircle
    .attr({
        fill: color,
        'fill-opacity': 1,
        'stroke': 'none',
        'stroke-color': 'transparent',
        'stroke-opacity' : 0
    });

    shockCircle
    .animate({
        r: radius
    }, 1500, '<');
}

function correctIpadSvgFill (el) {
    el = el.nodeName ? el : el[0]
    //    if (window.navigator.userAgent.indexOf("iPad") > -1) {
    //iOS SVG fills use an upside-down coordinate system
    var pattern,
    attributes = el.attributes,
    i,il;
        
    // Viewport dimension, this is affected by zoom
    var viewportwidth = window.innerWidth;
    var zoomAmount = initialWidth/viewportwidth;
    
    for(i = 0, il = attributes.length; i < il; i++) {
        if(attributes[i].name === "fill") {
            pattern = document.getElementById(attributes[i].value.replace(/(url(#|))/g, ''));
            pattern.setAttribute("patternTransform", "scale(" + 0.5 + ", " + 0.5  + ")");
            return pattern;
        }
    }

//    }

}

function handleBaloons(){

    $('.baloon-wrapper').each(function(index){
        var baloon = $(this);

        var $w = $(this).width();

        var paper = new Raphael(this, $w, $(this).height());
        var radius = $w / 2;
        var circle = paper.circle(radius, radius, 60);

        circle
        .attr({
            r: 1,
            fill: '#fff',
            'fill-opacity': 1,
            'stroke': 'none',
            'stroke-color': 'transparent',
            'stroke-opacity' : 0
        });

        circle
        .animate({
                
            r: radius,
            'fill-opacity': baloon.data('opacity')
        }, 1200, 'bounce', function(){
            
            if(baloon.hasClass('image')){
                var circle = paper.circle(radius, radius, radius);
                circle
                .attr({
                    'fill-opacity' : 0,
                    fill: 'url(' + baloon.attr('data-src') + ')',
                    'stroke': 'none',
                    'stroke-color': 'transparent',
                    'stroke-opacity' : 0
                });
                
                if(isiPad)
                    correctIpadSvgFill(circle);

                circle.animate({
                    'fill-opacity' : 1
                }, 200);
        
            }

            if(shockCircle.removed == false)
                shockCircle.remove();
            
        });
    });
}

function fadeInSite(){
    $('#navigation').fadeIn(500);
}

/*******************************************************************************
 * POSIZIONE / MOVIMENTO SEZIONI
 ******************************************************************************/
function disposeSections(){
    if(!isiPad && !isiPhone){		
        $('#home-section').css({
            top: window_height,
            left: window_width
        });

        $('#about-section').css({
            top: 0,
            left: window_width
        });

        $('#story-section').css({
            top:window_height,
            left: 0
        });

        $('#foto-section').css({
            top: window_height,
            left: window_width*2
        });

        $('#eksekusi-section').css({
            top: window_height*2,
            left: window_width
        });
    }
    
    if(isiPad){
        $('#home-section').css({
            top: 0,
            left: 0,
            'zIndex' : 1
        });
        //        $('#home-section').siblings().hide();

        $('#story-section').css({
            top:-window_height,
            left: 0,
            'zIndex' : 5
        });
    
        $('#about-section').css({
            top:-window_height,
            left: 0,
            'zIndex' : 5
        });


        $('#foto-section').css({
            top:-window_height,
            left: 0,
            'zIndex' : 5
        });

        $('#eksekusi-section').css({
            top:-window_height,
            left: 0,
            'zIndex' : 5
        });
    }
    
}

function goToSection(e){
    if(!isiPad && !isiPhone){
        
        var id = $(this).attr('id');
        if(id == 'pulpfoto')
            id = 'foto';
        var $destination = null;
        id += '-section';
        
        if($('#' + id).size() > 0)
            $destination = $('#' + id);
        else
            $destination = $($(this).attr('href'));
        
        //        alert($destination.offset());
		//console.log($(this).attr('href'));
		if($(this).attr('id') == 'eksekusi' || $(this).attr('id') == 'back-eksekusi' || $(this).attr('id') == 'about' ||  $(this).attr('id') == 'back-about'){
			if(isSafari) bodyelem = $("body")
			else bodyelem = $("html,body")
        bodyelem.animate({
            scrollTop: $destination.offset().top,
            //scrollLeft: $destination.offset().left
        }, section_scroll);
		return false;
		}
        if(isSafari) bodyelem = $("body")
			else bodyelem = $("html,body")
        bodyelem.animate({
            scrollTop: $destination.offset().top,
            scrollLeft: $destination.offset().left
        }, section_scroll);
    }
        
    
    if(isiPad){
        id = $(this).attr('id');
        if(id == 'pulpfoto')
            id = 'foto';
    
        var $section = $('#' + id + '-section');
        
        if($section.size() == 0){
            $section = $($(this).attr('href'));
            id = $(this).attr('href');
        }
        else
            id += '-section';
        
        switch(id){
            case 'eksekusi-section':
                $section.css({
                    top:window_height,
                    left: 0,
                    'zIndex' : 5
                });
                
                $section.animate({
                    top: 0,
                    left: 0
                }, section_scroll);
                
                break;
            case 'foto-section':
                $section.css({
                    top:0,
                    left: window_width,
                    'zIndex' : 5
                });
                
                $section.animate({
                    top: 0,
                    left: 0
                }, section_scroll);
                
                break;
            case 'story-section':
                $section.css({
                    top:0,
                    left: -window_width,
                    'zIndex' : 5
                });
                
                $section.animate({
                    top: 0,
                    left: 0
                }, section_scroll);
                
                break;
            case 'about-section':
                //                $section.css({
                //                    top:window_height,
                //                    left: 0,
                //                    'zIndex' : 5
                //                });
                
                $section.animate({
                    top: 0,
                    left: 0
                }, section_scroll);
                
                break;
            case '#home-section':
                var $active_section = $('.active-section');
                var active_id = $active_section.attr('id');
                
                //                alert(active_id);
                switch(active_id){
                    case 'eksekusi-section':
                        $active_section.animate({
                            top:window_height,
                            left: 0
                        }, section_scroll, function(){
                            $active_section.css({
                                top: -window_height,
                                left: 0
                            }, section_scroll);
                        });
                
                        break;
                    case 'foto-section':
                        $active_section.animate({
                            top:0,
                            left: window_width
                        }, section_scroll, function(){
                            $active_section.css({
                                top: -window_height,
                                left: 0
                            }, section_scroll);
                        });
                
                        break;
                    case 'story-section':
                        $active_section.animate({
                            top:0,
                            left: -window_width
                        }, section_scroll, function(){
                            $active_section.css({
                                top: -window_height,
                                left: 0
                            }, section_scroll);
                        });
                
                        break;
                    case 'about-section':
               
                        $active_section.animate({
                            top: -window_height,
                            left: 0
                        }, section_scroll, function(){
                            $active_section.css({
                                top: -window_height,
                                left: 0
                            }, section_scroll);
                        });
                
                        break;
                }
                
                break;
        }
    //        
    }
    
    $('.active-section').removeClass('active-section');
    id = $(this).attr('id');
    
    if(id == 'pulpfoto')
        id = 'foto';
    
    id += '-section';
    $('#' + id).addClass('active-section');
    if($('#' + id).size() == 0)
        $($(this).attr('href')).addClass('active-section');
    
    //    e.preventDefault();
    //    e.stopPropagation();
    return false;
}

/*******************************************************************************
 * GESTIONE foto
 ******************************************************************************/
function loadfoto(e){
    $('#foto-section .foto-loader').fadeIn(fade_loader);
    $.ajax({
        type: 'GET',
        url: $(this).attr('href'),
        dataType : 'json',
        success:showfoto
    });
    e.preventDefault();
    e.stopPropagation();
}

function showfoto(data){
    if(data.empty == true){
        alert('data error');
        return;
    }
    
    $('.work-wrapper.visible .foto-loader').hide();
    $('.work-wrapper.visible').removeClass('visible');
        
    $newWork = $('#clone-work').clone();
    $newWork.attr('id', '');
    $newWork.height(window_height);
    $newWork.find('.work-content').height(window_height);
    $newWork.find('.work-content').width(window_height);
    $newWork.find('.category-logo').append('<img src="' + data.categoryLogo + '" />');
    if(isiPad || isiPhone){
        $('img').retina();
            
        src = $newWork.find('.category-logo img').attr('src');
        newSrc = src.substring(0, src.length - 4)
        newSrc += '@2x.png';
        $newWork.find('.category-logo img').attr('src', newSrc);
    }
    
    /**
     * gestione links
     */
    $prev = $newWork.find('.prev-work');
    $next = $newWork.find('.next-work');
    if(data.first == true){
        $prev.hide()
    }else{
        $prev.attr('href', data.prev_link);
        $prev.bind('click', showPrevWork);
    }
    
    if(data.last == true){
        $next.hide()
    }else{
        $next.attr('href', data.next_link);
        $next.bind('click', loadNextWork);
    }
    
    
    
    $newWork.find('.work-content').css({
        'margin-left' : -(window_height) / 2
    });    
    
    
    $newWork.css({
        left: window_width
    });

    $('#foto-section').append($newWork);

    bindNewWork();
    
    $newWork.show();


    $newWork.find('.work-explanation').append('<p>' + data.description + '</p>');
    
    $slider = $newWork.find('.work-image-wrapper');
    $.each(data.images, function(){
        $img = $('<img />');
        $img.attr('src', '/foto_images/' + this.thumb);
        $img.attr('data-big', '/foto_images/' + this.big);

        $slider.append($img);
    });
    
    $slider.orbit({
        animation: 'fade',
        timer: true,
        animationSpeed: 800,
        directionalNav:false,
        bullets:true,
        pauseOnHover:true,
        startClockOnMouseOut: true,
        afterSlideChange:function(){
            $('.work-wrapper.visible .work-content img').each(function(){
                var myLeft =  ($(this).width() - $(this).parent().width()) / 2;
                if($(this).width() < $(this).parent().width())
                    myLeft *= -1;
        
                $(this).css({
                    left: myLeft
                });
            });
        }
    });
    
    $slider.find('img').load(function(){

    	$(this).css({
        	'left' : ($(this).parent().width() - $(this).width()) / 2
    	});
    });
    
    $slider.find('img').bind('click', zoomImage);
    $('.orbit-wrapper').css('height', '100%');
    
    //    if(!isiPhone)
    sliderHeight = window_height - 200;
    //    else
    //        sliderHeight = 150;
    
    $newWork.find('.work-image').height(sliderHeight);

    $newWork.find('.work-image').css({
        'margin-top' : (window_height - sliderHeight) / 2
    });
    
    
    $('.work-wrapper.visible .work-content img').each(function(){
        var myLeft =  ($(this).width() - $(this).parent().width()) / 2;
        if($(this).width() < $(this).parent().width())
            myLeft *= -1;
        
        $(this).css({
            left: myLeft
        });
    });
    
    $newWork.animate({
        left: 0
    }, work_switch, function(){
        $(this).addClass('visible');
    });

    $newWork.prev().removeClass('visible');//se non c' niente prima non dovrebbe dare errore
    

    $('#foto-section .foto-loader').fadeOut(fade_loader);
    $('.work-wrapper.visible .foto-loader').fadeOut(fade_loader);
}

function bindNewWork(){
    $('.back-foto-section').unbind('click');
    $('.back-foto-section').bind('click', function(){
        $('.work-wrapper').animate({
            left: window_width
        }, work_switch, function(){
            $(this).addClass('hidden');
        });
    });
}

function loadNextWork(e){
    $loader = $('.work-wrapper.visible .foto-loader')
    $loader.css({
        opacity: 1,
        left:$(this).position().left - $loader.width(),
        top:$(this).position().top - ($loader.height() / 2)
            
    })
    .fadeIn(fade_loader);
        
    $.ajax({
        type: 'GET',
        url: $(this).attr('href'),
        dataType : 'json',
        success:showfoto
    });
    
    e.preventDefault();
    e.stopPropagation();
}

function showPrevWork(e){
    $actual = $('.work-wrapper.visible');
    $prevWork = $actual.prev();
    
    $actual.animate({
        left: window_width
    }, work_switch, function(){
        $(this).remove();
        $prevWork.addClass('visible');
    });
    
    e.preventDefault();
    e.stopPropagation();
}

function zoomImage(){
    $wrapper = $('.work-wrapper.visible .work-zoom');
    $loader = $wrapper.find('.foto-loader');
    $close = $wrapper.find('.zoom-close');
    
    $wrapper.css('line-height', window_height + 'px');
    
    $wrapper.fadeIn();
    $loader.show().css('opacity', 1);
    
    $img = $('<img />');
    $img.css('opacity', 0);
    
    $wrapper.append($img);
    
    $img.load(function(){
        var loadedImg = $(this);
        loadedImg.animate({
            opacity: 1
        });
        $loader.hide();
        
        $wrapper.niceScroll();
        
    }).attr('src', $(this).data('big'));
    
    $(window).resize(function(){
        $wrapper.css('line-height', window_height + 'px');
    });
    
    $close.bind('click', function(){
        $wrapper.fadeOut('fast',function(){
            $img.remove();
        });
        return false;
    });
}

/*******************************************************************************
 * GESTIONE eksekusi
 ******************************************************************************/
function contactMe(){

    if($("input[name=mail]").val()!="" && 
        $("input[name=mail]").val()!= $("input[name=mail]").prev().text() && 
        $("textarea[name=message]").val()!= "" &&
        $("textarea[name=message]").val()!= $("textarea[name=message]").prev().text() &&
        $("#uman-control").val()!=""){
        if($("#uman-control").val() == sum){
            $("#fill-in").animate({
                opacity:0
            });
            $.ajax({
                type:"POST",
                data:$(this).serialize(),
                url:$(this).attr("action"),
                dataType:'json',
                success:function(a){
                    $("#fill-in").html('<b>' + a.response + '</b>').animate({
                        opacity:1
                    });
                }
            })
        }else{
            $("#fill-in").html(addendum1+" + "+addendum2+"  &#x2260; "+' '+$("#uman-control").val()+'!!!').animate({
                opacity:1
            });
        }
    }else{
        $("#fill-in").html("* compila tutti i campi, grazie.").animate({
            opacity:1
        });
    }
    return false
}

/*******************************************************************************
 * CONTROLLO RESIZE
 ******************************************************************************/
function handleResize(e){
    
    
    window_height = $(window).height();
    window_width = $(window).width();
    
    if(!isiPhone){
        $('#holder').height($('html').innerHeight());
        $('section.section, .work-wrapper.visible').width(window_width);
        $('section.section, .section-label, .work-wrapper.visible').height(window_height);
    
        $('.work-wrapper.visible .work-content').width(window_height);
        $('.work-wrapper.visible .work-content').height(window_height);
        $('.work-wrapper.visible .work-content').css({
            'margin-left' : -(window_height) / 2
        });
    
    
        $('#eksekusi-content').css('margin-top', (window_height - $('#eksekusi-content').height()) / 2);
    
        sliderHeight = window_height - 200;
        $('.work-wrapper.visible .work-image').height(sliderHeight);
        $('.work-wrapper.visible .work-image').css({
            'margin-top' : (window_height - sliderHeight) / 2
        });
        
        $('.work-wrapper.visible .work-content img').each(function(){
            var myLeft =  ($(this).width() - $(this).parent().width()) / 2;
            if($(this).width() < $(this).parent().width())
                myLeft *= -1;
        
            $(this).css({
                left: myLeft
            });
        });
    
        //    $('body').height(window_height);
        if($('#home-active-page').size() > 0){
            disposeSections();
            $('html,body').animate({
                scrollTop: $('.active-section').offset().top,
                scrollLeft: $('.active-section').offset().left
            }, 0);
        }
    }else{
        $('.section, .work-wrapper.visible').each(function(){
            $(this).css('min-height',window_height);
        });
        
        $('.work-wrapper.visible').css('height', window_height);
        
    }



    
    return false;
    //e.stopPropagation();
}
